<?php

namespace LowCode;

use Illuminate\Support\Collection;
use LowCode\Support\Random;

class Menu
{
    private static Menu $instance;

    protected Collection $menus;

    public function __construct()
    {
        $this->menus = Collection::make();
    }

    /**
     * @return static
     */
    public static function make(): static
    {
        if (!isset(self::$instance) || !(self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * @param MenuRouter $builder
     * @return $this
     */
    public function addMenu(MenuRouter $builder): static
    {
        $this->menus->add($builder);
        return $this;
    }

    /**
     * @param array $group
     * @param callable|null $callback
     * @return MenuRouter
     */
    public static function group(array $group, callable $callback = null): MenuRouter
    {
        $menu = self::make();
        $count = $menu->menus->count();
        $title = $group['title']??"菜单栏".$count;
        $path = $group['path']??"/".($group['name']??"");
        $name = $group['name']?? Random::alpha();
        $component = $group['component']??"BasicLayout";
        $router = MenuRouter::make($title, $name, $path, $component);
        if ($callback&&is_callable($callback)){
            call_user_func($callback, $router);
        }
        self::make()->addMenu($router);
        return $router;
    }

    /**
     * @param string|string[]|null $menuPath
     * @return array
     */
    public static function getMenus(string|array $menuPath = null): array
    {
        if ($menuPath){
            if (is_string($menuPath)&&file_exists($menuPath)){
                require $menuPath;
            }
            if (is_array($menuPath)){
                foreach ($menuPath as $itemPath){
                    if (is_string($itemPath)&&file_exists($itemPath)){
                        require $itemPath;
                    }
                }
            }
        }
        return self::make()->toArray();
    }

    public function toArray(): array
    {
        return  $this->menus->toArray();
    }
}
